package org.csu.mypetstore.controller;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.AccountService;
import org.csu.mypetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/catalog")
public class CatalogController {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private AccountService accountService;

    @GetMapping("/view")
    public String view(HttpServletRequest req, Model model ){
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        return "catalog/main";
    }

    //----登录检测----//
    @PostMapping("/signonCheck")
    public String signonCheck(HttpServletRequest req,@RequestParam("username") String username, @RequestParam("password") String password, Model model) {
        String md5pass = DigestUtils.md5DigestAsHex(password.getBytes());
        Account account = accountService.getAccount(username, md5pass);
//        Account account = accountService.getAccount(username, password);
        HttpSession session = req.getSession();

        String value1 = req.getParameter("vCode");
        String value2 = (String) session.getAttribute("checkcode");
        Boolean isSame = false;
        if (value2.equalsIgnoreCase(value1)) {
            isSame = true;
        }
        if (account == null || !isSame) {
            if (!isSame) {
                String tips = "Invalid Verification Code.   Signon failed.";
                model.addAttribute("message", tips);
            } else {
                String tips = "Invalid username or password.  Signon failed.";
                model.addAttribute("message", tips);
            }
            return "account/signonForm";
        } else {
            account.setPassword(null);
            String tips = "";
            model.addAttribute("message", tips);
            model.addAttribute("account",account);
            session.setAttribute("account",account);
            return "catalog/main";
        }
    }
    //----登出操作----//
    @RequestMapping("/signout")
    public String signout(HttpServletRequest req, Model model){
        Account account = null;
        HttpSession session = req.getSession();
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        return "catalog/main";
    }

    @GetMapping("/viewCategory")
    public String viewCategory(String categoryId, Model model, HttpServletRequest req){
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        if(categoryId != null){
            Category category = catalogService.getCategory(categoryId);
            List<Product> productList = catalogService.getProductListByCategory(categoryId);
            model.addAttribute("category",category);
            model.addAttribute("productList", productList);
            return "catalog/category";
        }
        return "catalog/main";
    }

    @GetMapping("/viewProduct")
    public String viewProduct(String productId,Model model,HttpServletRequest req)
    {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        if(productId != null){
            Product product = catalogService.getProduct(productId);
            List<Item> itemList = catalogService.getItemListByProduct(productId);
            model.addAttribute("product",product);
            model.addAttribute("itemList",itemList);
            return "catalog/product";
        }
        return "catalog/category";
    }

    @GetMapping("/viewItem")
    public String viewItem(String itemId,HttpServletRequest req,Model model )
    {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;
        model.addAttribute("account",account);
        session.setAttribute("account",account);

        if(itemId != null){
            Item item = catalogService.getItem(itemId);
            String productId = item.getProductId();
            Product product = catalogService.getProduct(productId);
            model.addAttribute("item",item);
            model.addAttribute("product",product);
            return "catalog/item";
        }
        return "catalog/product";
    }

    @GetMapping("/viewCart")
    public String viewCart(HttpServletRequest req,Model model){
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;

        if(account != null) {
            Cart cart = catalogService.getCartByUsername(account.getUsername());
            if (cart == null) {
                cart = new Cart();
            }

            List<CartItem> cartItemList = catalogService.getQuantityAndTotalByUsername(account.getUsername());
            for(int i=0;i<cart.getCartItemList().size();i++){
                cart.getCartItemList().get(i).setQuantity(cartItemList.get(i).getQuantity());
                cart.getCartItemList().get(i).setTotal(cartItemList.get(i).getTotal());
            }
            model.addAttribute("account",account);
            session.setAttribute("account",account);
            model.addAttribute("cart", cart);
            session.setAttribute("cart",cart);
            return "cart/cart";
        }
        else{
            return "account/signonForm";
        }
    }

    @GetMapping("/removeItem")
    public String removeItem(HttpServletRequest req, @RequestParam("workingItemId")String workingItemId,Model model){
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;
        catalogService.removeByUsernameAndItemId(account,workingItemId);

        Cart cart = catalogService.getCartByUsername(account.getUsername());

        List<CartItem> cartItemList = catalogService.getQuantityAndTotalByUsername(account.getUsername());
        for(int i=0;i<cart.getCartItemList().size();i++){
            cart.getCartItemList().get(i).setQuantity(cartItemList.get(i).getQuantity());
            cart.getCartItemList().get(i).setTotal(cartItemList.get(i).getTotal());
        }

        model.addAttribute("cart", cart);
        model.addAttribute("account",account);
        session.setAttribute("account",account);
        session.setAttribute("cart",cart);
        return "cart/cart";
    }

    @GetMapping("/addItemToCart")
    public String addItemToCart(HttpServletRequest req,Model model,@RequestParam("workingItemId")String workingItemId){
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account") ;

        if(account != null){
            Cart cart = catalogService.getCartByUsername(account.getUsername());

            List<CartItem> cartItemList = catalogService.getQuantityAndTotalByUsername(account.getUsername());
            for(int i=0;i<cart.getCartItemList().size();i++){
                cart.getCartItemList().get(i).setQuantity(cartItemList.get(i).getQuantity());
                cart.getCartItemList().get(i).setTotal(cartItemList.get(i).getTotal());
            }

            if(cart == null){
                cart = new Cart();
            }else{
                if (cart.containsItemId(workingItemId)) {
                    cart.incrementQuantityByItemId(workingItemId);
                } else {
                    boolean isInStock = catalogService.isItemInStock(workingItemId);
                    Item item = catalogService.getItem(workingItemId);
                    cart.addItem(item, isInStock);
                }
                catalogService.insertCartItem(account, cart);
            }
            model.addAttribute("cart", cart);
            model.addAttribute("account",account);
            session.setAttribute("account",account);
            session.setAttribute("cart",cart);
            return "cart/cart";
        }else{
            return "account/signonForm";
        }
    }

    @GetMapping("/updateCart")
    public void updateCart(Model model, HttpServletRequest req, HttpServletResponse response, @RequestParam("quantity") String quantity, @RequestParam("itemId") String itemId)throws IOException {
        HttpSession session = req.getSession();
        Account account = (Account)session.getAttribute("account");
        Cart cart = (Cart)session.getAttribute("cart");
        //Cart cart = catalogService.getCartByUsername(account.getUsername());
        String username = account.getUsername();
        String total = null;

        Iterator<CartItem> cartItemIterator = cart.getAllCartItems();

        CartItem cartItem = (CartItem) cartItemIterator.next();

        try {
            int newquantity = Integer.parseInt((String) quantity);
            cart.setQuantityByItemId(itemId, newquantity);

            String newquantity2 =  String.valueOf(newquantity);
            catalogService.ChangeItemQuantity(itemId,username,newquantity2, total);
            if (newquantity < 1) {
                cartItemIterator.remove();
                catalogService.removeByUsernameAndItemId(account,itemId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        model.addAttribute("cart",cart);
        session.setAttribute("cart", cart);

        Cart cart2 = (Cart)session.getAttribute("cart");
        Iterator<CartItem> cartItemIterator2 = cart2.getAllCartItems();
        String quantityAll = "";
        while (cartItemIterator2.hasNext()) {
            CartItem cartItem2 = cartItemIterator2.next();
            int quantity2 = cartItem2.getQuantity();
            quantityAll += quantity2 + "," + cartItem2.getTotal() + "," + cart2.getSubTotal()+",";
        }
        catalogService.insertCartItem(account,cart2);
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();
        out.write(quantityAll);
    }

    @GetMapping("/checkout")
    public String checkout(HttpServletRequest req,Model model){
        HttpSession session=req.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account != null) {
            Cart cart = catalogService.getCartByUsername(account.getUsername());
            if (cart == null) {
                cart = new Cart();
            }
            List<CartItem> cartItemList = catalogService.getQuantityAndTotalByUsername(account.getUsername());
            for (int i = 0; i < cart.getCartItemList().size(); i++) {
                cart.getCartItemList().get(i).setQuantity(cartItemList.get(i).getQuantity());
                cart.getCartItemList().get(i).setTotal(cartItemList.get(i).getTotal());
            }

            model.addAttribute("cart", cart);
            session.setAttribute("cart", cart);
            model.addAttribute("account", account);
            session.setAttribute("account", account);
        }
        if (account==null) {
            session.setAttribute("messageSignOn","You must sign on before attempting to check out. Please sign on and try checking out again.");
        }
        return "cart/checkout";
    }
}


